﻿#include "mainwidget.h"
#include "ui_mainwidget.h"
#include "additems.h"
#include "inputitem.h"
#include "totaldata.h"

#include <QTextCodec>
#include <QFlags>

QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");

MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWidget)
{
    ui->setupUi(this);
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

    connect2Mysql();
    // 取消窗口最大化功能
    setWindowFlags(windowFlags() & ~Qt::WindowMaximizeButtonHint);
    // 固定窗体大小
    setFixedSize(this->width(),this->height());

    // 初始化表格
    tableWidgetListInit();
}

MainWidget::~MainWidget()
{
    delete ui;
}

void MainWidget::connect2Mysql()
{
    db.setHostName("127.0.0.1");
    db.setUserName("用户名");
    db.setPassword("密码");
    db.setDatabaseName("数据库名称");

    if(!db.open()) {
        QMessageBox::critical(0,QObject::tr("Open database failed and the reason is :"),db.lastError().text());
    } else {
        QMessageBox::information(this,QStringLiteral("提示"),QStringLiteral("成功连接Mysql数据库！"));
    }

    //    QSqlQuery query(db);
    //    QString sql = QString("select * from commoditydatatable;");
}

void MainWidget::tableWidgetListInit()
{
    // id name num price supplier direator in out comment
    // 设置表格控件的行和列
    ui->tableWidget->setColumnCount(9);
    ui->tableWidget->setRowCount(200);

    // 设置字体
    ui->tableWidget->setFont(QFont("宋体",15));

    // 设置表格控件标题
    ui->tableWidget->setHorizontalHeaderLabels(QStringList() << QStringLiteral("编号") << QStringLiteral("名称") << QStringLiteral("数量") << QStringLiteral("单价") << QStringLiteral("供应商") << QStringLiteral("负责人") << QStringLiteral("入库时间") << QStringLiteral("出库时间") << QStringLiteral("备注"));

    // 初始化每个单元格的宽度
    ui->tableWidget->setColumnWidth(0,80);
    ui->tableWidget->setColumnWidth(1,160);
    ui->tableWidget->setColumnWidth(2,80);
    ui->tableWidget->setColumnWidth(3,80);
    ui->tableWidget->setColumnWidth(4,280);
    ui->tableWidget->setColumnWidth(5,80);
    ui->tableWidget->setColumnWidth(6,280);
    ui->tableWidget->setColumnWidth(7,280);
    ui->tableWidget->setColumnWidth(8,300);
}

void MainWidget::tableWidgetWidthInit()
{
    ui->tableWidget->setColumnWidth(0,80);
    ui->tableWidget->setColumnWidth(1,160);
    ui->tableWidget->setColumnWidth(2,80);
    ui->tableWidget->setColumnWidth(3,80);
    ui->tableWidget->setColumnWidth(4,280);
    ui->tableWidget->setColumnWidth(5,80);
    ui->tableWidget->setColumnWidth(6,280);
    ui->tableWidget->setColumnWidth(7,280);
    ui->tableWidget->setColumnWidth(8,300);
}


void MainWidget::on_search_btn_clicked()
{
    // 数据初始化
    tableWidgetWidthInit();

    // ui->tableWidget->clear();

    QSqlQuery query;
    QString strid = "Stockid=";
    strid += ui->lineEdit_id->text();

    QString str = QString("select * from commoditydatatable where %1;").arg(strid);
    if(!query.exec(str)) {
        QMessageBox::critical(0,QObject::tr("select failed ! the reason is :"),query.lastError().text());
    }

    int i = 0;
    while (query.next()) {
        QString res = query.value(0).toString();
        QString resName = query.value(1).toString();
        QString resNum = query.value(2).toString();
        QString resPrice = query.value(3).toString();
        QString supplier = query.value(4).toString();
        QString director = query.value(5).toString();
        QString inTime = query.value(6).toString();
        QString outTime = query.value(7).toString();
        QString comment = query.value(8).toString();
        // 测试 res 和 resName
        // QMessageBox::information(this,"Test",res + " " + resName);

        // 将数据显示在表格中
        ui->tableWidget->setItem(i,0,new QTableWidgetItem(res));
        ui->tableWidget->setItem(i,1,new QTableWidgetItem(resName));
        ui->tableWidget->setItem(i,2,new QTableWidgetItem(resNum));
        ui->tableWidget->setItem(i,3,new QTableWidgetItem(resPrice));
        ui->tableWidget->setItem(i,4,new QTableWidgetItem(supplier));
        ui->tableWidget->setItem(i,5,new QTableWidgetItem(director));
        ui->tableWidget->setItem(i,6,new QTableWidgetItem(inTime));
        ui->tableWidget->setItem(i,7,new QTableWidgetItem(outTime));
        ui->tableWidget->setItem(i,8,new QTableWidgetItem(comment));
        i++;
    }

}

void MainWidget::on_add_btn_clicked()
{
    AddItems *addDlg = new AddItems;
    addDlg->show();
}

void MainWidget::on_del_btn_clicked()
{
    int iClick = QMessageBox::warning(this,"Warning","Whether to delete ?",QMessageBox::Yes | QMessageBox::No);

    if(iClick == QMessageBox::Yes) {
        int iRow = ui->tableWidget->currentRow();
        QString strValue = ui->tableWidget->model()->index(iRow,0).data().toString();

        // QMessageBox::information(this,"Test",strValue);
        QSqlQuery query;
        if(strValue.isEmpty()) {
            QMessageBox::critical(this,"Warning","The id can not be null !");
            return;
        }

        QString sql = QString("delete from commoditydatatable where Stockid=%1").arg(strValue);
        if(query.exec(sql)) {
            QMessageBox::information(this,"Tip","Delete data successfully!!");
            ui->tableWidget->clear();
        } else {
            QMessageBox::critical(this,"Error","Delete failed and the reason is :",query.lastError().text());
        }
    }
}

void MainWidget::on_in_btn_clicked()
{
    InputItem *inputDlg = new InputItem;
    inputDlg->show();
}

void MainWidget::on_out_btn_clicked()
{

}

void MainWidget::on_outputData_btn_clicked()
{
    QDateTime time;
    QString strTemp;

    time = QDateTime::currentDateTime();
    strTemp = time.toString("yyyy-MM-dd hh:mm:ss");

    // 文件对话框
    QString strFileName = QFileDialog::getSaveFileName(this, tr("Excel Files"), QString("./%1%2.xls").arg(strTemp).arg("_XXgl"), tr("Excel Files(*.xls)"));

    if (!strFileName.isEmpty()) { // 使用 isEmpty() 检查文件名
        QAxObject *excel = new QAxObject;
        if (excel->setControl("Excel.Application")) {
            excel->dynamicCall("SetVisible (bool Visible)", false);
            excel->setProperty("DisplayAlerts", false);

            QAxObject *workbooks = excel->querySubObject("Workbooks");
            QAxObject *workbook = workbooks->dynamicCall("Add()").value<QAxObject*>(); // 添加工作簿

            QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1);
            QAxObject *cell;

            // 设置表头
            for (int i = 1; i <= ui->tableWidget->columnCount(); ++i) {
                cell = worksheet->querySubObject("Cells(int,int)", 1, i);
                cell->setProperty("RowHeight", 38);
                QString headerText = ui->tableWidget->horizontalHeaderItem(i - 1) ?
                            ui->tableWidget->horizontalHeaderItem(i - 1)->data(0).toString() : "";
                cell->dynamicCall("SetValue(const QString&)", headerText);
            }

            // 填充数据
            for (int j = 2; j <= ui->tableWidget->rowCount() + 1; ++j) { // 注意这里的 +1
                for (int k = 1; k <= ui->tableWidget->columnCount(); ++k) {
                    cell = worksheet->querySubObject("Cells(int,int)", j, k);
                    QTableWidgetItem *item = ui->tableWidget->item(j - 2, k - 1);
                    QString cellText = item ? item->text() : ""; // 检查 item 是否为空
                    cell->dynamicCall("SetValue(const QString&)", cellText + "\t");
                }
            }

            // 保存工作簿
            workbook->dynamicCall("SaveAs(const QString&)", QDir::toNativeSeparators(strFileName));
            workbook->dynamicCall("Close()");
            excel->dynamicCall("Quit()");
            delete excel;
            excel = nullptr;
        } else {
            qDebug() << "Failed to create Excel application.";
        }
    } else {
        qDebug() << "File name is empty.";
    }
}

void MainWidget::on_Data_btn_clicked()
{
    Totaldata *dataDlg = new Totaldata;
    dataDlg->show();
}
